package com.inspector.app.ui.plot

import android.app.ProgressDialog
import android.view.View
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.efb.module.ui.search.MapSearchFragment
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.inspector.app.BuildConfig
import com.inspector.app.R
import com.inspector.app.di.location.LocationInstance
import com.inspector.app.ui.flight.maplayer.SwitchMapLayerFragment
import com.inspector.app.util.ConstantUtil
import com.inspector.app.util.LogUtil
import com.inspector.app.util.SharedPreferencesUtils
import com.inspector.app.util.ToastUtil
import com.mapsforge.map.EfbLatLngPoint
import com.mapsforge.map.EfbMap
import com.mapsforge.map.vtm.AppExecutors
import com.mapsforge.map.vtm.VtmEfbMap
import com.mapsforge.map.vtm.VtmEfbMapView
import com.mapsforge.org.oscim.map.IDJMap
import java.lang.ref.WeakReference


/**
 * 地图加载相关
 */
class PlotMapLifecycleObserver(
    private val fragment: PlotFragment,
    private val viewModel: PlotViewModel,
) : DefaultLifecycleObserver {

    private val TAG: String = PlotMapLifecycleObserver::class.java.simpleName
    private var vtmEfbMapView: VtmEfbMapView? = null
    private val fragRef: WeakReference<PlotFragment> by lazy {
        WeakReference(fragment)
    }

    val efbMap: EfbMap get() = vtmEfbMapView!!.map
    val dMap: IDJMap get() = vtmEfbMapView!!.dMap

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        LogUtil.e(TAG, "标绘 onCreate")
        val plotFragment = fragRef.get() ?: return
        if (plotFragment.viewBinding.vsFlightMap.isInflated) return
        plotFragment.viewBinding.vsFlightMap.viewStub?.inflate()?.let { view ->
            setupView(viewStubInflate = view)
        }
    }

    private fun setupView(viewStubInflate: View) {
        setupMapView(viewStubInflate).also {
            vtmEfbMapView = it
        }

        setMapPosition()
    }

    private fun setupMapView(inflate: View): VtmEfbMapView {
        LogUtil.e(TAG, "加载地图 setupView")
        val efbMapView = inflate.findViewById<VtmEfbMapView>(R.id.efbMapView)
        efbMapView.setupView(ConstantUtil.BASE_DIR, BuildConfig.TianDiTuAppKey)

        // TODO: 夜间模式
//        efbMapView.map.setTheme(EfbMap.MapThemes.DEFAULT)

        //[默认 矢量图层]
        val vectorLayerIndex = EfbMap.MapType.entries.toMutableList().indexOf(EfbMap.MapType.Vector)
        val lastCheckedPos = SharedPreferencesUtils.getInt(
            ConstantUtil.USERID,
            ConstantUtil.MAP_LAYER_TYPE,
            vectorLayerIndex
        )
        val mapType = EfbMap.getMapTypeByIndex(lastCheckedPos)

        //[默认设置天地图矢量图图层]
        val finalMapType = if ((efbMapView.map as VtmEfbMap).layerNeedDownload(mapType)) {
            EfbMap.MapType.T_Vector
        } else {
            mapType
        }
        efbMapView.map.mapType = finalMapType

        val mapLayerIndex = EfbMap.MapType.entries.toMutableList().indexOf(finalMapType)
        SharedPreferencesUtils.put(ConstantUtil.USERID, ConstantUtil.MAP_LAYER_TYPE, mapLayerIndex)
        return efbMapView
    }


    /**
     * 点击定位功能
     */
    fun setMapPosition() {
        if (vtmEfbMapView?.map == null) return
        val location = LocationInstance.getInstance().lastKnownLocation ?: return
        (vtmEfbMapView?.map as VtmEfbMap).setPostion(EfbLatLngPoint(location.latitude, location.longitude))
    }


    /**
     * 切换图层
     */
    private var loadingRef: WeakReference<ProgressDialog>? = null
    fun switchMapLayer(view: View) {
        val fragment = fragRef.get() ?: return
        val efbMap = vtmEfbMapView?.map ?: return
        SwitchMapLayerFragment.create(view) { _, item ->
            if (item == null) return@create
            loadingRef?.get()?.dismiss()
            loadingRef?.clear()
            loadingRef = null
            val loadingDialog =
                ProgressDialog.show(fragment.requireContext(), "", "正在尽全力切换图层...", true)
            loadingRef = WeakReference(loadingDialog)

            AppExecutors.getInstance().diskIO().execute {
                if (!(efbMap as VtmEfbMap).layerNeedDownload(item.mapType) { succeed ->
                        if (loadingDialog.isShowing) {
                            loadingDialog.dismiss()
                        }
                        if (succeed) {
                            AppExecutors.getInstance().mainThread().execute {
                                efbMap.mapType = item.mapType
                            }
                        }
                    }) {
                    if (loadingDialog.isShowing) {
                        loadingDialog.dismiss()
                    }
                    efbMap.mapType = item.mapType
                }
            }
        }.show(fragment.childFragmentManager, null)
    }


    /**
     * 地图搜索事件
     */
    fun mapSearch() {
        val plotFragment = fragRef.get() ?: return
        MapSearchFragment.showDialog(plotFragment.childFragmentManager, checked = true) {}
    }


    /**
     * 标绘按钮展开收起
     */
    fun expandCollapse() {
        val fragment = fragRef.get() ?: return
        val collapsed = fragment.viewBinding.mapControl.collapsed
        fragment.viewBinding.mapControl.collapsed = collapsed != true
        fragment.viewBinding.mapControl.executePendingBindings()
    }


    fun closeDragView(bottomSheetChildView: View) {
        val behavior = BottomSheetBehavior.from(bottomSheetChildView)
        if (behavior.state == BottomSheetBehavior.STATE_COLLAPSED) {
            setPlotDrawMode(DrawMode.NONE)
            return
        }
        behavior.state = BottomSheetBehavior.STATE_COLLAPSED
    }


    /**
     * 设置标绘编辑模式
     */
    fun setPlotDrawMode(drawMode: DrawMode) {
        viewModel.drawMode.value = drawMode
    }

    /**
     * 保存标绘数据
     */
    fun savePlotData() {
        // TODO: [保存编辑数据]
        val drawMode = viewModel.drawMode.value ?: return
        val plotItem = viewModel.plotItem.value?.copy() ?: return
        when (drawMode) {
            DrawMode.POINT -> { //[保存标绘点数据]
                ToastUtil.getInstance().showToast("添加地标点")
                plotItem.name = "测试航点"
            }
            else -> {}
        }

        viewModel.drawMode.value = DrawMode.NONE //[退出编辑模式]
        viewModel.plotItem.value = plotItem
    }







    //============================ [生命周期部分 start] ============================
    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        vtmEfbMapView?.onResume()
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        vtmEfbMapView?.onPause()
    }

    override fun onDestroy(owner: LifecycleOwner) {
        onDestroyView()
        super.onDestroy(owner)
    }

    private fun onDestroyView() {
        vtmEfbMapView?.onDestroy()
        vtmEfbMapView = null
        fragRef.clear()
    }

}